/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.ekuma.epos.businesslogic;

import java.util.ArrayList;
import java.util.List;

import cn.ekuma.epos.bean.util.erp.OrderHelper;
import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.datalogic.businesslogic.OrderCalcManager;

import com.openbravo.data.basic.BasicException;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.sales.TaxesException;
import com.openbravo.pos.sales.TaxesLogic;
import com.openbravo.bean.erp.Order;
import com.openbravo.bean.erp.OrderLine;
import com.openbravo.bean.erp.OrderType;
import com.openbravo.bean.AttributeSetInstance;
import com.openbravo.bean.Customer;
import com.openbravo.bean.Product;

/**
 * 
 * @author Administrator
 */
public class OrderUtil {

	public static String ORDERTYPE_Normal = AppLocal
			.getIntString("label.orderbearing.normal");
	public static String ORDERTYPE_Revoerse = AppLocal
			.getIntString("label.orderbearing.reverse");

	public static OrderType ORDERTYPE_POS = new OrderType(null,
			OrderType.STORE_Out, OrderType.STORE_NoChange, null, "POS",
			OrderType.PRICETYPE_SellPrice, OrderType.PRICE_NoChange, "POS",
			OrderType.CONSULTTYPE_Null, OrderType.FUNDTYPE_In, null,
			OrderType.ORDERLINETYPE_SupportAll, true, null);

	public static void changeRate(Order m_oOrder, Double changedRant) {

	}

	/**
	 * 在加一个单据项时进行前期处理工作:
	 * 1.如果单据有参照类型,则应对其进行填冲(分为当前实时库存,时间片库存的参考量进行设置,如果是单据,参考量进行设置（价格可以通过导入方式完成)
	 * *2.如果货客商有各自的价格表,进行价格调整(后备
	 * 
	 * @param m_dlSales
	 * @param m_oOrder
	 * @param line
	 * @throws BasicException 
	 */
	public static void updateOrderLineConsultMultiply(I_DataLogicERP m_dlSales,
			Order m_oOrder, OrderLine line) throws BasicException {
		OrderType oType = m_oOrder.getDefineType();
		if (oType.getConsultType() != OrderType.CONSULTTYPE_Null
				&& line.getProductID() != null) {
			Double consultUnits = new Double(0);
			if (oType.getConsultType() == OrderType.CONSULTTYPE_Order
					&& m_oOrder.getConsultRef() != null) {
				String orderId = m_oOrder.getConsultRef();
				String productId = line.getProductID();
				String attsetinst = line.getProductAttSetInstId();
				consultUnits = m_dlSales.getProductUnitsInOrder(orderId,productId, attsetinst);
			} else if (oType.getConsultType() == OrderType.CONSULTTYPE_RealStore
					&& m_oOrder.getLocationRef() != null) {
				String location = m_oOrder.getLocationRef();
				String productId = line.getProductID();
				String attsetinst = line.getProductAttSetInstId();
				consultUnits = m_dlSales.getProductUnitsInRealStore(location, productId, attsetinst);
				
			} else if (oType.getConsultType() == OrderType.CONSULTTYPE_TimeSliceStore
					&& m_oOrder.getConsultRef() != null) {
				String timeStoreId = m_oOrder.getConsultRef();
				String productId = line.getProductID();
				String attsetinst = line.getProductAttSetInstId();
				consultUnits = m_dlSales.getProductUnitsInTimeStore(timeStoreId, productId, attsetinst);
			}
			if(consultUnits==null)
				consultUnits = new Double(0);
			line.setConsulMultiply(consultUnits);
		}
	}

	public static double chiocePrice(I_DataLogicERP dlSales, Order m_oOrder,
			Product product) throws BasicException {
		return getProductPrice(dlSales,
				m_oOrder.getDefineType().getPriceType(), product,
				m_oOrder.getCustomer());
	}

	public static double chioceConsultPrice(I_DataLogicERP dlSales,
			Order m_oOrder, Product product) throws BasicException {
		return getProductPrice(dlSales, m_oOrder.getDefineType()
				.getConsultPriceType(), product, m_oOrder.getCustomer());
	}

	public static double getProductPrice(I_DataLogicERP dlSales, int priceType,
			Product product, Customer customer) throws BasicException {
		Double retPrice = new Double(0);
		if (OrderType.PRICETYPE_BuyPrice == priceType)
			retPrice = product.getPriceBuy();
		else if(OrderType.PRICETYPE_SellPrice == priceType)
			retPrice = product.getPriceSell();
		else if (OrderType.PRICETYPE_CustomerPrice == priceType){
			if(customer != null)
			    retPrice = product.getM_dCustomerPrice() == 0 ? product.getPriceSell() : product.getM_dCustomerPrice();
			else
				retPrice =  product.getPriceSell();  
		}else if (OrderType.PRICETYPE_CustomerCategoryPrice == priceType) {
			if(customer != null&&customer.getCategoryid()!=null)
				retPrice = dlSales.findCustomerCategoryPrice(product.getID(),customer.getCategoryid());
			if(retPrice==null||retPrice==0)
			  retPrice = product.getM_dCustomerPrice() == 0 ? product.getPriceSell() : product.getM_dCustomerPrice();
		}else if (OrderType.PRICETYPE_WholesalePrice == priceType) {
			  retPrice = product.getM_dWholesalePrice() == 0 ? product.getPriceSell() : product.getM_dWholesalePrice();
		}else if (OrderType.PRICETYPE_WholesaleCustomerCategoryPrice == priceType) {
			if(customer != null&&customer.getCategoryid()!=null){
				retPrice = dlSales.findCustomerCategoryWholesalePrice(product.getID(),customer.getCategoryid());
				
			}
			if(retPrice==null||retPrice==0)
			  retPrice = product.getM_dWholesalePrice() == 0 ? product.getPriceSell() : product.getM_dWholesalePrice();
		}
		return retPrice;
	}
	
	public static void addOrderLineForAllReadyList(I_DataLogicERP dlSales,Order newOrder,List<OrderLine> oldLines) throws BasicException{
		OrderLine newline;
		Product product;
		for(OrderLine line:oldLines){
			newline=line.copyOrderLine();
			newline.setPriceRate(1);
			if(newline.getLineStyle() == OrderLine.PRODUCTLINE){
			   product=dlSales.getProductInfo(newline.getProductID());
			   if(product!=null){
				   Double price=chiocePrice(dlSales,newOrder,product);
				   newline.setPrice(price);
				   newline.setDefaultPrice(price);
				   newline.setConsultPrice(chioceConsultPrice(dlSales,newOrder, product));
				   addOrderLine(dlSales,newOrder,newline);
			   }else 
				   throw new BasicException(AppLocal.getIntString("message.noproduct")+":"+newline.getProductName());
			}else
				addOrderLine(dlSales,newOrder,newline);
		}
	}
	
	
    public static  void addOrderLine(I_DataLogicERP dlSales,Order m_oOrder,OrderLine oLine) throws BasicException {
            OrderType oType = m_oOrder.getDefineType();
            if (!oType.orderLineAddAble(oLine.getLineStyle())) {
                return;
            }
            if (!orderLineExistCheck(m_oOrder,oLine)) {
                    // Producto normal, entonces al finalnewline.getMultiply()
                    try {
						updateOrderLineConsultMultiply(dlSales, m_oOrder, oLine);
						ArrayList<OrderLine> lines=(ArrayList<OrderLine>) m_oOrder.getLines();
						lines.add(oLine);
					} catch (BasicException e) {
						throw new BasicException(AppLocal.getIntString("message.updateOrderLineConsultMultiplyError"));
					}
            }
        
    }    
    
    private static boolean orderLineExistCheck(Order m_oOrder,OrderLine oLine){
        OrderType oType = m_oOrder.getDefineType();
        boolean existed = false;
        if (oLine.getLineStyle() == OrderLine.PRODUCTLINE) {
                if (oType.getOrderLineType() == OrderType.ORDERLINETYPE_SupportUniqueProduct || oType.getOrderLineType() == OrderType.ORDERLINETYPE_SupportUniqueProductAndService) {
                	for(OrderLine line:m_oOrder.getLines()){
                        String curAttId=line.getProductAttSetInstId();
                        if(oLine.getProductID().equalsIgnoreCase(line.getProductID()))
                            if(curAttId==null&&oLine.getProductAttSetInstId()==null||curAttId!=null&&curAttId.equals(oLine.getProductAttSetInstId())){
                            	existed = true;
                                break;
                            }
                    }
                } else if (oType.getOrderLineType() == OrderType.ORDERLINETYPE_SupportUniqueProductAddAndService || oType.getOrderLineType() == OrderType.ORDERLINETYPE_SupportUniqueProductAdded) { 
                    for(OrderLine line:m_oOrder.getLines()){
                        String curAttId=line.getProductAttSetInstId();
                        if(oLine.getProductID().equalsIgnoreCase(line.getProductID()))
                            if(curAttId==null&&oLine.getProductAttSetInstId()==null||curAttId!=null&&curAttId.equals(oLine.getProductAttSetInstId())){
                            	existed = true;
                            	line.setMultiply(line.getMultiply() + oLine.getMultiply());
                                break;
                            }
                    }
                }
            }
         return existed;
    }
    
    public static Order reCalcOrder(Order order,OrderCalcManager orderCalcManager,TaxesLogic taxeslogic) throws TaxesException, BasicException{
    	taxeslogic.calculateTaxes(order);
        orderCalcManager.calcOrder(order);
    	order.setTotalPrice(OrderHelper.getTotal(order));
        order.setTotalTax(OrderHelper.getTax(order));
        order.setTotalConsultPrice(OrderHelper.getTotalConsultValue(order));
    	return order;
    }

	public static void choiceProductAttibuteValuePrice(Order m_oOrder,
			OrderLine line, AttributeSetInstance attributeSetInstance) {
		 OrderType oType = m_oOrder.getDefineType();
	    if (line.getLineStyle() != OrderLine.PRODUCTLINE) 
	    	return;
	    int priceType = m_oOrder.getDefineType().getPriceType();
	    if (OrderType.PRICETYPE_BuyPrice == priceType){
	    	line.setAttrPrice(attributeSetInstance.getDiffPriceCost());
            line.setAttrPriceCost(attributeSetInstance.getDiffPrice());
	    }else {
		   line.setAttrPrice(attributeSetInstance.getDiffPrice());
           line.setAttrPriceCost(attributeSetInstance.getDiffPriceCost());
		}
	}
}
